package com.reshare;

import com.alibaba.fastjson.JSON;
import com.reshare.base.ResultInfo;
import com.reshare.exceptions.NoLoginException;
import com.reshare.exceptions.ParamsException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class GlobalException implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception e) {
        //未登录异常
        if (e instanceof NoLoginException) {
            ModelAndView mav = new ModelAndView("redircet:/index");
            return mav;
        }
        //设默认值
        ModelAndView mav = new ModelAndView();
        mav.setViewName("success");
        mav.addObject("code", 400);
        mav.addObject("msg", "系统异常，请稍后访问");
        e.printStackTrace();
        //判断
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            ResponseBody responseBody = handlerMethod.getMethod().getDeclaredAnnotation(ResponseBody.class);
            //判断responseBody是否为空
            if (responseBody == null) {
                if (e instanceof ParamsException) {
                    ParamsException pe = (ParamsException) e;
                    mav.addObject("code", pe.getCode());
                    mav.addObject("msg", pe.getMsg());
                }
            } else {
                ResultInfo resultInfo = new ResultInfo();
                resultInfo.setCode(300);
                resultInfo.setMsg("系统异常，请重试");
                e.printStackTrace();
                if (e instanceof ParamsException) {
                    ParamsException pe = (ParamsException) e;
                    resultInfo.setMsg(pe.getMsg());
                    resultInfo.setCode(pe.getCode());
                }
                //设置编码格式
                resp.setContentType("application/json;charset=utf-8");
                //输出
                PrintWriter out = null;
                try {
                    out = resp.getWriter();
                    //json-->String
                    out.write(JSON.toJSONString(resultInfo));
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                } finally {
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                }
            }
        }
        return null;
    }
}
